package com.jxs.android.ges;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.xmlpull.v1.XmlPullParserException;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.InputFilter;
import android.text.InputFilter.LengthFilter;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.jxs.android.ges.data.SenderInfo;
import com.jxs.android.soap.BuWebService;
import com.jxs.android.soap.IWebService;
import com.jxs.android.soap.SoapUtil;
import com.jxs.android.util.HandlerHolder;
import com.jxs.android.util.MemoryUtil;
import com.jxs.android.weiget.BuAlertDailog;
import com.jxs.android.weiget.BuLoadingDailog;
import com.jxs.android.weiget.TopBar;

@SuppressLint("HandlerLeak")
/**
 * 预览短信并发送
 * @author jxs
 *
 */
public class WorkLogGetSenderInfoList extends AbstractActivity {
	// 2.4.6 getSmsContent 【获取发送页面内容】
	private BuLoadingDailog progressDialog;
	private Context context;
	private PhoneAdapter adapter;
	private ArrayList<SenderInfo> senderInfos = new ArrayList<SenderInfo>();
	private String content = "";
	private String senderInfo = "";
	private ArrayList<String> phones = new ArrayList<String>();

	private EditText send_conent;// 电话号码
	private ListView phone_list;// 分公司

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		context = this;
		initTopBar(savedInstanceState, R.layout.bu_work_log_get_sender_info_list);
		initUI();
		if (null != getIntent()) {
			content = getIntent().getStringExtra("content");
			senderInfo = getIntent().getStringExtra("senderInfo");
			phones = getIntent().getStringArrayListExtra("phones");
		}
		getSenderInfoList();
		adapter = new PhoneAdapter();
		phone_list.setAdapter(adapter);
	}

	private void initUI() {
		send_conent = (EditText) findViewById(R.id.send_conent);// 工号
		InputFilter[] filters = { new LengthFilter(800) };
		send_conent.setFilters(filters);
		send_conent.setEnabled(false);
		phone_list = (ListView) findViewById(R.id.phone_list);// 分公司

	}

	@Override
	public void topBarLogic(TopBar topBar) {
		super.topBarReturn(topBar);
		topBar.setLogicBtnText("发送短信");
		topBar.setTitle("短信预览");
		topBar.showLogicBtn();
		topBar.hindFilter();
		topBar.hindSpinnerBtn();
		topBar.setLogicBtnListern(new TopBar.LogicBtnListern() {
			@Override
			public void onClickLogicBtn() {

				List<String> phones = new ArrayList<String>();

				for (SenderInfo d : senderInfos) {
					if ("1".equals(d.send_flag)) {
						phones.add(d.acc_nbr);
					}
				}

				if (phones.isEmpty() || phones.size() == 0) {
					errorMsgPop("无可发送的号码！");
					return;
				}

				progressDialog.show();
				new WorkLogSendSmsHolder(handler).sendSms(GesApplication.getUserInfo().getTicket(), content, senderInfos);
			}
		});
	}

	private void getSenderInfoList() {
		progressDialog = new BuLoadingDailog(this);
		progressDialog.showLoading(R.string.load_and_wait);
		new Thread(new Runnable() {
			@Override
			public void run() {
				getSenderInfoList(GesApplication.getUserInfo().getTicket());
			}
		}).start();
	}

	private String getValue(List<String> items) {

		StringBuilder rs = new StringBuilder("");

		for (int id = 0; id < items.size(); id++) {
			rs.append(items.get(id));
			if (id != (items.size() - 1))
				rs.append("|");
		}

		return rs.toString();
	}

	private void getSenderInfoList(String ticket) {
		// 2.4.8 getSenderInfoList 【判别号码列表是否可以发送（获取预览内容）】
		String wsdl_url = GesApplication.WSDL_URL;// wsdl
		String namespace = GesApplication.WSDL_NAME_SPACE;// namespace
		String methodName = "getSenderInfoList";// 要调用的方法名称
		SoapObject request = new SoapObject(namespace, methodName);
		request.addProperty("ticket", ticket);
		request.addProperty("phoneList", getValue(phones));
		request.addProperty("content", content);
		request.addProperty("senderInfo", senderInfo);

		BuWebService webService = new BuWebService(wsdl_url, request);
		webService.setDoNet(false);
		webService.requestWSDL(new IWebService() {
			@Override
			public void logic(SoapSerializationEnvelope envelope) throws IOException, XmlPullParserException {
				SoapObject response = (SoapObject) envelope.getResponse();
				paser(response);
			}

			@Override
			public void error(String message, Exception e) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			}

		});
	}

	private void paser(SoapObject soapObject) {
		if (null != soapObject) {
			String stauts = soapObject.getProperty("status").toString();
			SoapObject msgObjec = (SoapObject) soapObject.getProperty("msg");
			String message = msgObjec.getProperty("message").toString();
			if ("-2".equals(stauts)) {
				Message msg = new Message();
				msg.what = ERROR_MSG;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("-1".equals(stauts)) {
				Message msg = new Message();
				msg.what = TO_LOGIN;
				msg.obj = message;
				handler.sendMessage(msg);
			} else if ("0".equals(stauts)) {
				Message msg = new Message();
				msg.what = UPDATE_LIST_UI;
				content = SoapUtil.getValue(soapObject, "content");
				msg.obj = (SoapObject) soapObject.getProperty("retMsg");
				handler.sendMessage(msg);
			}
		}
	}

	private final int UPDATE_LIST_UI = 0x101;
	private final int ERROR_MSG = 0x1013;
	private final int TO_LOGIN = 0x1019;
	private Handler handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			if (!MemoryUtil.isCurrentActivity(WorkLogGetSenderInfoList.class)) {
				return;
			}
			if (null != progressDialog && progressDialog.isShowing()) {
				progressDialog.dismiss();
			}
			if (msg.what == UPDATE_LIST_UI) {
				send_conent.setText(content);
				initContentData((SoapObject) msg.obj);
			} else if (msg.what == ERROR_MSG) {
				errorMsgPop(msg.obj.toString());
			} else if (msg.what == TO_LOGIN) {
				errorMsgToLogin(msg.obj.toString());
			} else if (msg.what == HandlerHolder.What.WORK_LOG_SEND_SMS_RESLT_OK) {
				// show(msg.obj.toString());
				show();
			}
		}
	};

	private void show() {
		errorMsgPop("短信发送成功！", new BuAlertDailog.IPhoneAlertDailog() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.cancel();
				finish();
			}

			@Override
			public String getOkText(Context context) {
				return getString(R.string.promp_confirm);
			}
		});
	}

	@Deprecated
	void show(final String message) {

		BuAlertDailog.builder(context, "提示", message, new BuAlertDailog.AlertOkAndCancelListener() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.cancel();
				finish();
			}

			@Override
			public String getOkText(Context context) {
				return "再次发送短信";
			}

			@Override
			public String getCancleText(Context context) {
				return getString(R.string.prompt_cancel);
			}

			@Override
			public void cancelLogic(Dialog dialog) {
				dialog.cancel();
				setResult(RESULT_OK);
				finish();
			}
		}).show();

	}

	private void initContentData(SoapObject retMsgObject) {
		if (null != retMsgObject) {
			for (int i = 0; i < retMsgObject.getPropertyCount(); i++) {
				SoapObject taskBeanObject = (SoapObject) retMsgObject.getProperty(i);
				SenderInfo senderInfo = new SenderInfo();

				senderInfo.acc_nbr = SoapUtil.getValue(taskBeanObject, "acc_nbr");// 手机号码
				senderInfo.latnid = SoapUtil.getValue(taskBeanObject, "latnid");// 区号（手机号码的区号为空）
				senderInfo.product_top_lvl_name = SoapUtil.getValue(taskBeanObject, "product_top_lvl_name");// 产品类型
				senderInfo.send_flag = SoapUtil.getValue(taskBeanObject, "send_flag");// 是否可以发送标示（1可发送，2不能发送）
				senderInfo.serv_id = SoapUtil.getValue(taskBeanObject, "serv_id");// 用户ID
				senderInfo.serv_name = SoapUtil.getValue(taskBeanObject, "serv_name");// 用户名称
				senderInfo.type_note = SoapUtil.getValue(taskBeanObject, "type_note");// 提示内容

				senderInfos.add(senderInfo);
			}
		}
		adapter.notifyDataSetChanged();
	}

	private class PhoneAdapter extends BaseAdapter {

		class ViewHolder {
			TextView index;// 手机号码
			TextView acc_nbr;// 手机号码
			TextView latnid;// 区号（手机号码的区号为空）
			TextView product_top_lvl_name;// 产品类型
			TextView send_flag;// 是否可以发送标示（1可发送，2不能发送）
			TextView serv_id;// 用户ID
			TextView serv_name;// 用户名称
			TextView type_note;// 提示内容
		}

		private LayoutInflater inflater = null;
		private ViewHolder holder = null;

		public PhoneAdapter() {
			inflater = LayoutInflater.from(context);
		}

		public int getCount() {
			return senderInfos.size();
		}

		public SenderInfo getItem(int position) {
			return senderInfos.get(position);
		}

		public long getItemId(int position) {
			return position;
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			final SenderInfo contact = senderInfos.get(position);
			if (convertView == null) {
				convertView = inflater.inflate(R.layout.bu_work_log_get_sender_info_list_item, null);
				holder = new ViewHolder();
				holder.index = (TextView) convertView.findViewById(R.id.index);// 手机号码
				holder.acc_nbr = (TextView) convertView.findViewById(R.id.acc_nbr);// 手机号码
				// holder.latnid = (TextView)
				// convertView.findViewById(R.id.latnid);// 区号（手机号码的区号为空）
				holder.product_top_lvl_name = (TextView) convertView.findViewById(R.id.product_top_lvl_name);// 产品类型
				holder.send_flag = (TextView) convertView.findViewById(R.id.send_flag);// 是否可以发送标示（1可发送，2不能发送）
				holder.serv_id = (TextView) convertView.findViewById(R.id.serv_id);// 用户ID
				holder.serv_name = (TextView) convertView.findViewById(R.id.serv_name);// 用户名称
				// holder.type_note = (TextView)
				// convertView.findViewById(R.id.type_note);// 提示内容
				convertView.setTag(holder);
			} else {
				holder = (ViewHolder) convertView.getTag();
			}
			holder.index.setText(String.valueOf(position + 1));
			holder.acc_nbr.setText(contact.acc_nbr);

			if ("1".equals(contact.send_flag)) {
				holder.product_top_lvl_name.setText(contact.product_top_lvl_name);
				holder.serv_name.setText(contact.serv_name);
				holder.send_flag.setText(Html.fromHtml("<font color=green>可发送</font>"));
			} else {
				holder.product_top_lvl_name.setText("");
				holder.serv_name.setText(contact.type_note);
				holder.send_flag.setText(Html.fromHtml("<font color=red>不能发送</font>"));
			}

			convertView.setOnLongClickListener(new View.OnLongClickListener() {

				@Override
				public boolean onLongClick(View v) {
					showDelete(contact);
					return false;
				}
			});

			return convertView;
		}
	}

	private void showDelete(final SenderInfo contact) {

		BuAlertDailog.builder(this, "提示", "确定移除该号码？", new BuAlertDailog.AlertOkAndCancelListener() {

			@Override
			public void okLogic(Dialog dialog) {
				dialog.cancel();
				senderInfos.remove(contact);
				adapter.notifyDataSetChanged();
			}

			@Override
			public String getOkText(Context context) {
				return "移除";
			}

			@Override
			public String getCancleText(Context context) {
				return getString(R.string.prompt_cancel);
			}

			@Override
			public void cancelLogic(Dialog dialog) {
				dialog.cancel();
			}
		}).show();

	}

	@Override
	protected void onDestroy() {
		setResult(RESULT_OK);
		super.onDestroy();
	}
}
